package bitset;

import java.util.Arrays;
import java.util.BitSet;

public class MyBitSet {
    private byte[] elem;
    private int useSize;

    public MyBitSet() {
        this.elem = new byte[1];
    }

    public MyBitSet(int size) {
        if(size < 0) {
            throw new IndexOutOfBoundsException("设置的大小无效");
        }
        int num = size / 8 + 1;

        this.elem = new byte[num];
    }


    public void set(int val) {
        int index = val / 8;
        if(index >= elem.length) {
            elem = Arrays.copyOf(elem, (index + 1) * 2);
        }
        elem[index] |= (1 << (val % 8));
        useSize++;
    }


    public boolean get(int val) {
        int index = val / 8;
        if(index >= elem.length) {
            return false;
        }

        if((elem[index] & (1 << (val % 8))) == 0) {
            return false;
        }

        return true;
    }

    public boolean remove(int val) {
        int index = val / 8;
        if(index >= elem.length) {
            return false;
        }

        elem[index] &= (~(1 << (val % 8)));
        useSize--;

        return true;
    }

    public int size() {
        return useSize;
    }

    public static void main(String[] args) {
        int[] arr = {1,5,6,8,12,15,19,23};
        MyBitSet myBitSet = new MyBitSet(1);
        for (int i = 0; i < arr.length; i++) {
            myBitSet.set(arr[i]);
        }

        System.out.println(myBitSet.size());
        for (int i = 0; i < arr.length; i++) {
            System.out.println(myBitSet.get(arr[i]));
        }

        for (int i = 0; i < arr.length; i++) {
            myBitSet.remove(arr[i]);
            System.out.println(myBitSet.get(arr[i]));
        }

    }
}
